/*
	Copyright (c) 2008, Grant Jones <grant@podtronics.com>.
	All rights reserved.

	Redistribution and use in source and binary forms, with or
	without modification, are permitted provided that the following
	conditions are met:

		Redistributions of source code must retain the above copyright
		notice, this list of conditions and the following disclaimer.
		
		Redistributions in binary form must reproduce the above copyright
		notice, this list of conditions and the following disclaimer in
		the documentation and/or other materials provided with the
		distribution.
		
		Neither the name of the gxjones.com nor the names of its
		contributors may be used to endorse or promote products derived
		from this software without specific prior written permission.
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
	FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
	OF THE POSSIBILITY OF SUCH DAMAGE.
	
	http://www.opensource.org/licenses/bsd-license.php
*/

/*
 *  edb_dump.c
 *  edb
 *
 *  Created by Grant Jones on 5/24/08.
 *
 */
#include "edb_main.h"
#include "edb_msg_parser.h"
#include "edb_msg_utils.h"
#include "edb_msg_expr.h"
#include "strmap.h"
#include "edb_domain.h"
#include "edb_domain_select.h"
#include "edb_domain_index.h"
#include "cmap_sort.h"

#include <time.h>


int edb_dump_as_tags( const char *filename )
{
	TagManagerStruct *src = tagm_open(filename);
	tagm_dumpTag( src, stdout, 0ULL, 0 );
	tagm_close(src);
	return 0;
}

/* takes a set of attributes and creates a "INSERT INTO <domain_name> VALUES( <attrs> );"
** statement in net format (preamble + attribute header + attributes) */
cmapStruct *edb_dump_make_str( mempool_t *pool, const char *domain_name, size_t domain_name_len, AttrList *attrs )
{
	cmapStruct *resp_str= cmap_new(pool);
	strmapEnumStruct sme;
	AttrValue *attr_val;
	char *attr_key;
	size_t attr_key_sz;
	int bFirstAttr;	
//"PREAMBLE WITH PARAMETERS AS $parameter1, $parameter2;\r\n
//<item count>\r\n
//<key_1_name> <bytes>, <key_2_name> <bytes>\r\n
//<key_1_data>\r\n
//<key_2_data>\r\n"
	
	cmap_str_append_bytes(resp_str, "INSERT INTO ", 12 );
	cmap_str_append_bytes(resp_str, domain_name, domain_name_len );
	cmap_str_append_bytes(resp_str, " VALUES( ", 9);
	
	strmap_enum( attrs, &sme );
	bFirstAttr = 1;
	while( (attr_val = strmap_enum_next( &sme, &attr_key, &attr_key_sz )) )
	{
		if( bFirstAttr )
			bFirstAttr = 0;
		else
			cmap_str_append_bytes(resp_str, ", ", 2);

		cmap_str_append_bytes(resp_str, attr_key, attr_key_sz );
		cmap_str_append_bytes(resp_str, ":$", 2);
		cmap_str_append_bytes(resp_str, attr_key, attr_key_sz );
	}
	
	cmap_str_append_bytes(resp_str, " );\r\n1\r\n", 7 );
	
	strmap_enum( attrs, &sme );
	bFirstAttr = 1;
	while( (attr_val = strmap_enum_next( &sme, &attr_key, &attr_key_sz )) )
	{
		if( bFirstAttr )
			bFirstAttr = 0;
		else
			cmap_str_append_bytes(resp_str, ", ", 2);

		cmap_str_append_bytes(resp_str, attr_key, attr_key_sz );
		cmap_str_append_bytes(resp_str, " ", 1);
		cmap_str_concat(resp_str, "%ld", attr_val->value.n );
	}
	cmap_str_append_bytes(resp_str, "\r\n", 2 );
	
	strmap_enum( attrs, &sme );
	bFirstAttr = 1;
	while( (attr_val = strmap_enum_next( &sme, &attr_key, &attr_key_sz )) )
	{
		cmap_str_append_bytes(resp_str, (const char *)attr_val->value.z, attr_val->value.n );
		cmap_str_append_bytes(resp_str, "\r\n", 2);
	}	

	return resp_str;
}

#define OMIT_DOMAIN_LIST_INFO

int edb_dump_as_EDBSQL( ProgramContextStruct *pcs )
{
	rtree_t *rt = pcs->rt_db_ptr;
	TagManagerEnumStruct tmes;
	TagStruct *tag;
	off_t tag_loc;
	strmapStruct *domains_ls = cmap_new(NULL);
	
	strmapEnumStruct domain_key_e;
	char *domain_name;
	size_t domain_name_len;
	rtvalue_t wildcard_key = { 0, NULL };
	rtenum_t rte;
	rtvalue_t found_key, found_data;	
#ifndef OMIT_DOMAIN_LIST_INFO	
	cmapStruct *dls_debug_str = cmap_new(NULL);
#endif	
	FILE *fp_out = stdout;
	rtree_use( rt, NULL, 0 );			/* position list cursor at root */
	

	/* note we use the tag-level enumeration, not the
	** higher-level radix-tree enumeration */
	
	/* Step 1: Gather domains that are contained in the DB file: */
	
	if( tagm_beginEnumTags( rt->tms, &tmes, rt->list_cursor ) )
		return -1;


	/* debug stuff: */
#ifndef OMIT_DOMAIN_LIST_INFO	
	{
		time_t cur_tm = time(NULL);
		cmap_str_concat(dls_debug_str, "CREATE TIME: %sDOMAIN LIST:\n", ctime(&cur_tm));
	}
#endif	
	while( (tag = tagm_nextTag( rt->tms, &tmes, &tag_loc )) )
	{
		if( tag->hdr.bFlags & TAG_OVERFLOW || tag->hdr.bFlags & TAG_DELETED )
			continue;
		off_t *tag_loc_copy = (off_t *)mempool_malloc_named(domains_ls->mempool, sizeof(off_t), "index tag location" );
		if(!tag_loc_copy)
			continue;

		*tag_loc_copy = tag_loc;
		strmap_assign(domains_ls, (const char *)tag->key, tag->hdr.klen, tag_loc_copy );

#ifndef OMIT_DOMAIN_LIST_INFO		
		cmap_str_append_bytes(dls_debug_str, (const char *)tag->key, tag->hdr.klen);		
		cmap_str_concat(dls_debug_str, "\n");
#endif		
	}
	tagm_endEnumTags(rt->tms, &tmes);	


#ifndef OMIT_DOMAIN_LIST_INFO
	{
		size_t debug_info_len;
		char *debug_cstr = cmap_str_join(dls_debug_str, &debug_info_len);
		
		fprintf(fp_out, ";\r\n1\r\ndebug_info %ld\r\n", (long)debug_info_len-1 );
		fwrite(debug_cstr, debug_info_len-1, 1, fp_out);
	}
#endif	
	/* Step 2: For each domain we get retrieve an item and print it out... over and over */
	
	strmap_enum(domains_ls, &domain_key_e);

	while( (strmap_enum_next(&domain_key_e, &domain_name, &domain_name_len)) )
	{

	
		rtree_use( rt, NULL, 0 );			/* position list cursor at root */	
		rtree_use( rt, domain_name, domain_name_len );
		rtree_use( rt, EDB_NAME_KEY, strlen(EDB_NAME_KEY) );	
	
		rt_enumerate_begin( rt, &rte, NULL, &wildcard_key );

		while( rt_enumerate_next( &rte, &found_key, &found_data ) == 0 )
		{
			AttrList *attrs_out = NULL;
			mempool_t result_item_pool;
			mempool_init_named( &result_item_pool, CMAP_POOL_INIT_SZ, "Domain Dump Data Item" );
			/* destruct will create an AttrList out of the raw data returned by 
			** the enumerate operation, it makes a copy of the data allocating
			** new memory */
			
			edb_domain_destruct_item( &result_item_pool, &found_data, &attrs_out );
			
			cmapStruct *dump_str = edb_dump_make_str( &result_item_pool, domain_name, domain_name_len, attrs_out );
			size_t dump_str_len;
			char *dump_cstr = cmap_str_join(dump_str, &dump_str_len);
			
			fwrite( dump_cstr, dump_str_len-1, 1, fp_out );
			
			mempool_destroy(&result_item_pool);
		}

		/* needs to be moved to radixtree_enum: */
		cmap_destroy(rte.key_stack);		
	}
	
	
	
	
	
	rtree_close( pcs->rt_db_ptr );
	return 0;
}



